import React from 'react';
import { Row, Col, Select, Input, Button, Table, Card, Pagination, message, Icon,Form,  DatePicker , Modal, Cascader, Tooltip ,Message} from 'antd';
import { getRecordList, delRecordList, getRecrodByfid, exportServiceRecord} from '../../services/api';
import { connect } from 'dva';
import { formatCascader } from '../../common/common'
import ModalData from './modal';
import moment from 'moment';
import './index.less';
import {fileDownLoad} from '../../config/index';

const Option = Select.Option;
const FormItem = Form.Item;
const confirm = Modal.confirm;
const RangePicker = DatePicker.RangePicker;
@Form.create()
class Record extends React.Component {
	state = {
    searchObj: {},
    pageParam: {
      current: 1,
      pageSize: 10,
      total: 1
    },
    dataSource: [],
    selectedRowKeys: [],

    area:'',   
		name:'',
		Sname:'',
		content:'',
    servicePeople:'',
    fQuantumTimeBegin:null,
    fQuantumTimeEnd:null,

    dataInfo:'',   //服务记录导出地址,
    loading:false,
    
	};

	componentDidMount(){
		this.props.dispatch({type: 'example/setServicePersons',res:this.props.servicePersons});   //服务负责人
		this.props.dispatch({type: 'example/setServiceType',res:this.props.serviceType});  //服务内容
    this.props.dispatch({type: 'example/setAreaInfo',res:this.props.areaInfo});  //区域
    this.firstFetch();
  }
  
  async firstFetch() {
    this.setState({loading:true})
    const response = await getRecordList({...this.state.searchObj, pageCurrent: this.state.pageParam.current, pageSize: this.state.pageParam.pageSize});
    if (response.code === 200) {
      if (response.data) {
        this.setState({
          dataSource: response.data.dataList,
          pageParam: {...this.state.pageParam, total: response.data.totalNumber},
          loading:false
        });
      }
    } else {
      this.setState({loading:false})
      response.msg && message.error(response.msg);
    }

  }

  // 翻页
  changePage = (e) => {
    this.setState({
      pageParam: {
        ...this.state.pageParam,
        current: e
      }
    }, ()=> {
      this.firstFetch()
    })
  }
  // 切换大小
  changePageSize = (e, size) => {
    this.setState({
      pageParam: {
        ...this.state.pageParam,
        current: 1,
        pageSize: size,
      }
    }, () => {
      this.firstFetch()
    })
  }

  //获取查询服务记录
  getInfo() {
      let fQuantumTimeBegin = this.state.fQuantumTimeBegin ? this.state.fQuantumTimeBegin: undefined;
      let fQuantumTimeEnd = this.state.fQuantumTimeEnd ? this.state.fQuantumTimeEnd: undefined;
      let fElderly = this.state.name? this.state.name : undefined;
      let fServiceStaff =this.state.Sname?this.state.Sname : undefined;
      let fServiceType = this.state.content?this.state.content:undefined ;
      let fStreetCommunity = this.state.area ? this.state.area[this.state.area.length - 1]: undefined;
    this.setState({
      searchObj:{
        fQuantumTimeBegin,
        fQuantumTimeEnd,
        fElderly,
        fServiceStaff,
        fServiceType,
        fStreetCommunity
      },
      pageParam: {
        ...this.state.pageParam,
        current: 1
      }
    }, ()=> {
      this.firstFetch();
    })
	}

  //导出服务记录
  async exportServiceRecord(){
    const response = await exportServiceRecord({
      fQuantumTimeBegin:this.state.fQuantumTimeBegin ? this.state.fQuantumTimeBegin: undefined,
      fQuantumTimeEnd:this.state.fQuantumTimeEnd ? this.state.fQuantumTimeEnd: undefined,
      fElderly:this.state.name? this.state.name : undefined,
      fServiceStaff:this.state.Sname?this.state.Sname : undefined,
      fServiceType:this.state.content?this.state.content:undefined,
      fStreetCommunity: this.state.area ? this.state.area[this.state.area.length - 1]: undefined,
      pageCurrent: 0,
			pageSize: 0
    });
    if(response.code === 200){
      this.setState({
        dataInfo:response.data,
        selectedRowKeys:[]
      },()=>{
        fileDownLoad(this.state.dataInfo,'派单备查表','xls'),
        Message.success('信息导出成功')
      })
    } else {
      response.msg && message.error(response.msg);

    }
  }

  onSelectChange = (e) => {
    this.setState({
      selectedRowKeys: e
    })
  }

  delete = () => {
    // 用户列表id集合
    const ids = this.state.selectedRowKeys;
    if (ids.length === 0) {
      message.warning('请至少选择一个记录');
      return;
    }
    confirm({
      title: '提示',
      content: `您确认要删除${ids.length}个记录吗?`,
      okText: '确认',
      cancelText: '取消',
      onOk: ()=> {
        // 一个loading的处理
        this.setState({ delLoading: true });
        return new Promise((resolve, reject)=> {
          this.setState({ delLoading: false });
          delRecordList(ids)
          .then((data)=>{
            this.setState({ delLoading: true });
            if (data.code === 200) {
              resolve(); // 成功的返回
              this.firstFetch();
              this.setState({
                selectedRowKeys:[],
                delLoading: false
              })  
              message.success('删除成功')  
            } else {
              this.setState({ delLoading: false });
              message.error(data.msg);
            }
          })
        }).catch(() => console.info('删除出错'),
        this.setState({ delLoading: false })
      );
      },
      onCancel:()=> {
        if (this.state.delLoading) {
          message.warning('处理中,请稍后');
          return new Promise((resolve, reject)=> {
            while (!this.state.delLoading) {
              resolve();
            }
          })
        }
      },
    });
  }

  
  info = async (fid) => {
    const response = await getRecrodByfid(fid);
    if (response.code === 200) { 
      if (response.data) {
        this.setState({
          recordData: response.data,
          showModal: true
        })
      }
    } else {
      message.error(response.msg);
    }
  } 

//时间段
onChange_= (dates, dateStrings) => {
  this.setState({
    fQuantumTimeBegin:new Date(dateStrings[0]),
    fQuantumTimeEnd: new Date(new Date(dateStrings[1]).getTime() + 24 * 60 * 60 * 1000)
  })
 }

 cancel = (val)=> {
  confirm({
    title: '提示',
    content: `您确认要取消 ${val.fElderly} 的预约吗?`,
    okText: '确认',
    cancelText: '取消',
    onOk: ()=> {
      // 一个loading的处理
      this.setState({ delLoading: true });
      return new Promise((resolve, reject)=> {
        delRecordList([val.fId]).then((res)=>{
          if(res.code === 200) {
            message.success(res.msg);
            this.firstFetch();
            delLoading: false
          }else{
            this.setState({ delLoading: false });
            message.error(res.msg);
          }
          resolve();
        })
      }).catch(() => console.info('删除出错'));
    },
    onCancel:()=> {
      // message.warning('处理中,请稍后');
      // return new Promise((resolve, reject)=> {
      //   while (!this.state.delLoading) {
          // resolve();
      //   }
      // })
    },
  });
 }

 
 disabledDate = (current) => {
  return current > moment().endOf('day');
 }

	render() {
		const { loading, selectedRowKeys } = this.state;
		const rowSelection = {
		  selectedRowKeys,
		  onChange: this.onSelectChange,
    };
    const columns = [{
      title: '服务日期',
      className: 'columnTitle',
      dataIndex:'fBegintime',
      fixed: 'left',
      width: 170
    }, {
      title: '老人姓名',
      className: 'columnTitle',
      dataIndex:'fElderly',
      width: 170
    }, {
      title: '老人电话',
      className: 'columnTitle',
      dataIndex:'fPhone',
      width: 170
    }, {
      title: '街办区域',
      className: 'columnTitle',
      dataIndex:'fStreetCommunity',
      width: 250
    }, {
      title: '服务内容',
      className: 'columnTitle',
      dataIndex:'fContent',
      width: 170
    }, {
      title: '服务负责人',
      className: 'columnTitle',
      dataIndex:'fServiceStaff',
      width: 170
    }, {
      title: '服务次数',
      className: 'columnTitle',
      dataIndex:'fCount',
      width: 170,
      render:(val) => val === 0 ? '--' : `${val}次`,
    }, {
      title: '时长',
      className: 'columnTitle',
      dataIndex:'fDuration',
      width: 170,
      render: (val)=>`${val}小时`
    },, {
      title: '金额',
      className: 'record-content',
      dataIndex:'fSum',
      width: 170
    }, {
      title: '备注',
      className: 'columnTitle',
      dataIndex:'fRemarks',
      width: 250
    },{
      title: '回访情况',
      className: 'columnTitle',
      dataIndex:'fSatisfaction',
      width: 170
    }, {
      title: '操作',
      className: 'columnTitle',
      fixed: 'right',
      width: 100,
      render:(val)=>{
             return(
              <div>
                <Tooltip title="详情">
                <Icon type="bars" onClick={()=>this.info(val.fId)} style={{marginRight:10,color:"#3890FF",cursor:'pointer'}}/>
                </Tooltip>
                {
                  val.fState === 'a3eec264faeb4d95843ce0bd6268a162' ? 
                  <Tooltip title="取消预约">
                  <Icon type="rollback" onClick={()=>this.cancel(val)} style={{marginRight:10,color:"#3890FF",cursor:'pointer'}}/> 
                  </Tooltip>
                  : null
                }
              </div>
       )
      }
    }];
		return (
      // 
			<div style={{padding: '20px 40px'}}>  
        <Card >
				<div style={{display: 'flex'}}>
					<Row  className='searchDiv searchCard' type="flex" justify="space-around">
						<Col span={4} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>街办区域:</span>
							</Row>
							<Row>
								<Cascader style={{width: '100%'}} options={formatCascader(this.props.areaInfo, 'fId', 'fName', 'children')} onChange={(val)=>{this.setState({area:val})}} placeholder="请选择..." changeOnSelect/>
							</Row>
						</Col>
						<Col span={4} className='searchDivChildren'>
							<Row  style={{marginBottom: 10}}>
								<span className='titleSpan'>老人姓名:</span>
							</Row>
							<Row>
								<Input  placeholder="请输入..." value={this.state.name} onChange={(e)=>{this.setState({name:e.target.value})}}/>
							</Row>
						</Col>
						<Col span={4} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>服务人员姓名:</span>
							</Row>
							<Row>
								<Input placeholder="请输入..." value={this.state.Sname} onChange={(e)=>{this.setState({Sname:e.target.value})}}/>
							</Row>
						</Col>
						<Col span={4} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>服务内容:</span>
							</Row>
							<Row>
                  <Select style={{width:'100%'}} placeholder="请选择..." allowClear showSearch optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} onChange={(value)=>{this.setState({content:value})}}> 
                  {
                    this.props.serviceType.map((item)=>{
                      return(
                        <Option value={item.fId} key={item.fId}>{item.fName}</Option>
                      )
                    })
                  }
                </Select>
							</Row>
						</Col>
						<Col span={4} className='searchDivChildren'>
							<Row style={{marginBottom: 10}}>
								<span className='titleSpan'>服务时间段:</span>
							</Row>
							<Row>
                  <RangePicker
                    disabledDate={this.disabledDate}
                    ranges={{ '今天': [moment(), moment()], '当月': [moment(), moment().endOf('month')] }}
                    onChange={this.onChange_}
                  />
							</Row>
						</Col>
					</Row>
					<div style={{height: 67,lineHeight: '100px'}}>
					<Button type="primary" onClick={()=>this.getInfo()} >查询</Button>
					</div>
				</div>
				</Card>

				<div className="search">
				  <Button type="danger"  onClick={()=>this.delete()} >删除</Button>
          <Button onClick={()=>this.exportServiceRecord()} style={{background:'#bb9ffa',color:'white'}}>导出</Button>
				</div>

				<Card style={{marginTop: 10}}>
					<Table
            rowKey="fId"
						style={{marginBottom: 20}}
						columns={columns}
						dataSource={this.state.dataSource}
						pagination={false}
						locale={{
							emptyText: '暂无数据'
            }}
            scroll={{ x: true}}
            rowSelection={rowSelection}
            loading={loading}
					/>

           <Pagination size="small" 
            total={this.state.pageParam.total} 
            current={this.state.pageParam.current}
            pageSize={this.state.pageParam.pageSize}
						showSizeChanger
						showQuickJumper
						showTotal={(total)=>(<span>共{total}条</span>)}
						onChange={this.changePage}
						onShowSizeChange={this.changePageSize}
					/>
				</Card>
       
        <ModalData visable={this.state.showModal} operateModal={()=>this.setState({showModal: !this.state.showModal})} data={this.state.recordData}/>
			</div>
		)
	}
}

const service = Form.create()(Record)
export default connect((state)=>({
	oldDetailModal: state.example.oldDetailModal,
	addModal: state.example.addModal,
	distributeModal: state.example.distributeModal,
	areaInfo: state.example.areaInfo,
    serviceType:state.example.serviceType,
    servicePersons:state.example.servicePersons,
}))(service)


